<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { OrganizationApi } from '@/api/OrganizationApi.ts'
import type { OrganizationVO } from '@/api/Organization.ts'
import { TeamOutlined, UserOutlined, CalendarOutlined, InfoCircleOutlined } from '@ant-design/icons-vue'

const router = useRouter()

const loading = ref(false)
const organizations = ref<OrganizationVO[]>([])

const searchName = ref<string | null>(null)

const fetchOrganizations = async () => {
  loading.value = true
  try {
    const data = await OrganizationApi.search({
      name: searchName.value,
      status: null,
    })
    organizations.value = data?.records ?? []
  } catch (error) {
    console.error('获取组织列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  fetchOrganizations()
}

const handleReset = () => {
  searchName.value = null
  fetchOrganizations()
}

const handleCardClick = (org: OrganizationVO) => {
  // 跳转到组织详情页面
  console.log('点击组织:', org)
  // router.push({ name: 'organizationDetail', params: { id: org.id } })
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

onMounted(() => {
  fetchOrganizations()
})
</script>

<template>
  <div class="flex justify-center px-4 py-6 bg-gray-50">
    <div class="w-full max-w-[1080px]">
      <!-- 搜索栏 -->
      <a-card class="mb-6 rounded-lg shadow-sm">
        <div class="flex flex-wrap items-center gap-3">
          <a-input
            v-model:value="searchName"
            allow-clear
            placeholder="搜索组织名称"
            class="w-52"
            @pressEnter="handleSearch"
          />
          <a-button type="primary" @click="handleSearch">搜索</a-button>
          <a-button @click="handleReset">重置</a-button>
        </div>
      </a-card>

      <!-- 组织卡片网格 -->
      <div class="grid grid-cols-3 gap-4">
        <!-- 左侧组织列表（2列） -->
        <div class="col-span-2">
          <div v-if="loading" class="flex justify-center items-center py-20">
            <a-spin size="large" tip="加载中..." />
          </div>
          
          <div v-else class="grid grid-cols-2 gap-4">
            <a-card
              v-for="org in organizations"
              :key="org.id"
              hoverable
              class="rounded-lg shadow-sm cursor-pointer transition-all duration-300 hover:shadow-md"
              @click="handleCardClick(org)"
            >
              <div class="flex flex-col h-full">
                <!-- 组织名称 -->
                <div class="flex items-center mb-3">
                  <TeamOutlined class="text-blue-500 text-xl mr-2" />
                  <h3 class="text-lg font-semibold text-gray-800 truncate flex-1">
                    {{ org.name }}
                  </h3>
                </div>

                <!-- 组织描述 -->
                <p class="text-gray-600 text-sm mb-4 line-clamp-2 min-h-[40px]">
                  {{ org.description || '暂无描述' }}
                </p>

                <!-- 组织信息 -->
                <div class="space-y-2 text-sm text-gray-500 mt-auto">
                  <div class="flex items-center">
                    <UserOutlined class="mr-2" />
                    <span>成员数: {{ org.currentMembers }}</span>
                  </div>
                  <div class="flex items-center">
                    <CalendarOutlined class="mr-2" />
                    <span>创建于: {{ formatDate(org.createTime) }}</span>
                  </div>
                </div>
              </div>
            </a-card>

            <!-- 空状态 -->
            <div
              v-if="!loading && organizations.length === 0"
              class="col-span-2 text-center py-20"
            >
              <a-empty description="暂无组织数据" />
            </div>
          </div>
        </div>

        <!-- 右侧说明卡片 -->
        <div class="col-span-1">
          <div class="sticky top-6">
            <a-card class="rounded-lg shadow-sm bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-100">
              <div class="flex items-start mb-3">
                <InfoCircleOutlined class="text-blue-500 text-2xl mr-3 mt-1" />
                <h3 class="text-lg font-semibold text-gray-800">组织是什么？</h3>
              </div>
              
              <div class="space-y-4 text-gray-700">
                <p class="leading-relaxed">
                  创建组织后，将拥有内部题库、作业、竞赛（内部赛、邀请赛）等更多的功能。
                </p>
                
                <div class="bg-white rounded-lg p-4 shadow-sm">
                  <h4 class="font-medium text-gray-800 mb-2">核心功能</h4>
                  <ul class="space-y-2 text-sm">
                    <li class="flex items-start">
                      <span class="text-blue-500 mr-2">•</span>
                      <span>内部题库管理</span>
                    </li>
                    <li class="flex items-start">
                      <span class="text-blue-500 mr-2">•</span>
                      <span>作业布置与批改</span>
                    </li>
                    <li class="flex items-start">
                      <span class="text-blue-500 mr-2">•</span>
                      <span>竞赛组织与管理</span>
                    </li>
                    <li class="flex items-start">
                      <span class="text-blue-500 mr-2">•</span>
                      <span>成员权限管理</span>
                    </li>
                  </ul>
                </div>
              </div>
            </a-card>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
